<template>
  <span>
    <WaybillDeviceLoader v-if="isLoader"
                         :waybill-id="waybillId"
                         :waybillIdKeys="waybillIdKeys" />
    <span v-if="device && deviceCode">
      <div v-if="name==='positionAddress'">
        {{ device.positionAddress || '--' }}
      </div>
      <div v-if="name==='realStatus'">
        <span v-if="device.lithiumValue">
          <el-tag size="medium">{{ device.lithiumValue }}</el-tag>
          <br>
          <el-tag class="mt6"
                  size="medium">{{ device.status}}</el-tag>
        </span>
        <span v-else>--</span>
      </div>
      <div v-if="name==='transportStatus'">
        {{ device.transportStatusName || '--' }}
      </div>
      <div v-if="this.name === 'warning' && warningInfo">
        {{ warningInfo }}
      </div>
    </span>
    <div v-else>--</div>
  </span>
</template>

<script>
import { mapState } from "vuex";
import WaybillDeviceLoader from "@/components/basic/WaybillDeviceLoader.vue"
export default {
  name: 'ReactDevice',
  components: {
    WaybillDeviceLoader
  },
  props: {
    name: String,
    status: Number,
    trackType: Number,
    deviceCode: String,
    waybillId: Number
  },
  computed: {
    ...mapState({
      waybillDeviceTraces: (state) => state.deviceTrace.waybillDeviceTraces,
      waybillExpirationTime: (state) => state.deviceTrace.waybillExpirationTime
    }),
    expireAt () {
      return new Date().getTime() + 5 * 60 * 1000;
    },
    waybillIdKeys () {
      let keys = this.waybillDeviceTraces ? Object.keys(this.waybillDeviceTraces) : [];
      let ids = Array.from(keys, key => Number(key));
      return ids;
    },
    isLoader () {
      let flag = this.waybillIdKeys.includes(this.waybillId) ? false : true;
      if (new Date().getTime() > this.waybillExpirationTime) {
        this.$store.commit("deviceTrace/WAYBILL_CHANGEDEVICETRACE", {});
        this.$store.commit("deviceTrace/WAYBILL_EXPIRATIONTIME", this.expireAt);
      }
      return flag && ![40, 50].includes(this.status) && ((this.trackType === 1 && this.deviceCode) || this.trackType === 3)
    },
    device () {
      return this.waybillDeviceTraces[this.waybillId]
    },
    warningInfo () {
      if (this.device?.device?.warning?.message) {
        return this.device?.device?.warning?.message
      } else {
        return '--'
      }
    }
  },
  created () {
    if (new Date().getTime() > this.waybillExpirationTime) {
      this.$store.commit("deviceTrace/WAYBILL_CHANGEDEVICETRACE", {});
      this.$store.commit("deviceTrace/WAYBILL_EXPIRATIONTIME", this.expireAt);
    }
  }
}
</script>
<style scoped>
.mt6 {
  margin-top: 6px;
}
</style>